package queue;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.TimeUnit;

public class BlockingQueueDemo {

    /**
     * 队列大小
     */
    private static ArrayBlockingQueue<Object> objects = new ArrayBlockingQueue<>(3);

    public static void main(String[] args) {
        add();
//        addOffer();
//        addBlockingA();
//        addD();
//        add_D();
        get();
        getPoll();
//        getTake();
//        get_D();
//        getD();
//        getShowHead();

    }

    public static void add(){
        System.out.println(objects.add("a"));
        System.out.println(objects.add("b"));
        System.out.println(objects.add("c"));
    }

    public static void get(){
        System.out.println(objects.remove());
        System.out.println(objects.remove());
        System.out.println(objects.remove());
    }

    /**
     * 抛出异常 Queue full
     */
    public static void addD(){
        System.out.println(objects.add("d"));
    }

    /**
     * 抛出异常 NoSuchElementException
     */
    public static void getD(){
        System.out.println(objects.remove());
    }

    public static void add_D(){
        boolean d = objects.offer("d");
        System.out.println(d);
    }

    public static void get_D(){
        Object poll = objects.poll();
        System.out.println(poll);
    }

    public static void getShowHead(){
        //会抛出异常
        System.out.println(objects.element());
        for (int i = 0; i < 3; i++) {
            objects.remove();
            //取队首
            System.out.println(objects.peek());
        }
    }

    /**
     * 等待，阻塞。一直阻塞
     */
    public static void addBlockingA(){
        try {
            objects.put("d");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    /**
     * 等待，阻塞。一直阻塞
     */
    public static void getTake(){
        try {
            System.out.println(objects.take());
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    /**
     * 等待，阻塞。等待超时
     */
    public static void addOffer(){
        try {
            objects.offer("d",1,TimeUnit.SECONDS);
            System.out.println("任务超时！");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    /**
     * 等待，阻塞。等待超时
     */
    public static void getPoll(){
        try {
            Object poll = objects.poll(1,TimeUnit.SECONDS);
            System.out.println(poll);
            System.out.println("任务超时！");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }


}
